<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">



















  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext">
  






<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"hide","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="前言本文主要面向于初次接触 Flink、或者对 Flink 有了解但是没有实际操作过的同学。希望帮助大家更顺利地上手使用 Flink，并着手相关开发调试工作。">
<meta name="keywords" content="Flink">
<meta property="og:type" content="article">
<meta property="og:title" content="Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行">
<meta property="og:url" content="https://www.dudefu.tk/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html">
<meta property="og:site_name" content="The Future">
<meta property="og:description" content="前言本文主要面向于初次接触 Flink、或者对 Flink 有了解但是没有实际操作过的同学。希望帮助大家更顺利地上手使用 Flink，并着手相关开发调试工作。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1j6ho5j30j3095tcj.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1pn7ozj30qs0i40xb.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1wxus2j30q70jdgqe.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx296yn0j30r209y0v4.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx2lsgn1j30ez0cy414.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx31jdnsj30fg034jrn.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx37snbbj30po0bsmz7.jpg">
<meta property="og:updated_time" content="2021-01-20T01:46:41.817Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行">
<meta name="twitter:description" content="前言本文主要面向于初次接触 Flink、或者对 Flink 有了解但是没有实际操作过的同学。希望帮助大家更顺利地上手使用 Flink，并着手相关开发调试工作。">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1j6ho5j30j3095tcj.jpg">





  
  
  <link rel="canonical" href="https://www.dudefu.tk/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行 | The Future</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">The Future</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Stay hungry,stay foolish.</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档<span class="badge">125</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    
      
    

    <a href="/categories" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类<span class="badge">15</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    
      
    

    <a href="/tags" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签<span class="badge">63</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-something">

    
    
    
      
    

    
      
    

    <a href="/something" rel="section"><i class="menu-item-icon fa fa-fw fa-paper-plane"></i> <br>干货</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  
    <div class="reading-progress-bar"></div>
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.dudefu.tk/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Daniel X">
      <meta itemprop="description" content="專注于大数据技術，分享干货">
      <meta itemprop="image" content="https://hexoblog-1254111960.cos.ap-guangzhou.myqcloud.com/HexoBlog-tou.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="The Future">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2021-01-19 11:22:32" itemprop="dateCreated datePublished" datetime="2021-01-19T11:22:32+08:00">2021-01-19</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2021-01-20 09:46:41" itemprop="dateModified" datetime="2021-01-20T09:46:41+08:00">2021-01-20</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/大数据/" itemprop="url" rel="index"><span itemprop="name">大数据</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html" class="leancloud_visitors" data-flag-title="Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>本文主要面向于初次接触 Flink、或者对 Flink 有了解但是没有实际操作过的同学。希望帮助大家更顺利地上手使用 Flink，并着手相关开发调试工作。</p>
<a id="more"></a>
<p>课程内容包括：</p>
<ul>
<li>Flink 开发环境的部署和配置</li>
<li>运行 Flink 应用（包括：单机 Standalone 模式、多机 Standalone 模式和 Yarn 集群模式）</li>
</ul>
<h2 id="一、Flink-开发环境部署和配置"><a href="#一、Flink-开发环境部署和配置" class="headerlink" title="一、Flink 开发环境部署和配置"></a>一、Flink 开发环境部署和配置</h2><p>Flink 是一个以 Java 及 Scala 作为开发语言的开源大数据项目，代码开源在 GitHub 上，并使用 Maven 来编译和构建项目。对于大部分使用 Flink 的同学来说，Java、Maven 和 Git 这三个工具是必不可少的，另外一个强大的 IDE 有助于我们更快的阅读代码、开发新功能以及修复 Bug。因为篇幅所限，我们不会详述每个工具的安装细节，但会给出必要的安装建议。</p>
<p>关于开发测试环境，Mac OS、Linux 系统或者 Windows 都可以。如果使用的是 Windows 10 系统，建议使用 Windows 10 系统的 Linux 子系统来编译和运行。</p>
<table>
<thead>
<tr>
<th style="text-align:left">工具</th>
<th style="text-align:left">注释</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Java</td>
<td style="text-align:left">Java 版本至少是Java 8，且最好选用 Java 8u51 及以上版本</td>
</tr>
<tr>
<td style="text-align:left">Maven</td>
<td style="text-align:left">必须使用 Maven 3，建议使用 Maven 3.2.5。Maven 3.3.x 能够编译成功，但是在 Shade 一些 Dependencies 的过程中有些问题</td>
</tr>
<tr>
<td style="text-align:left">Git</td>
<td style="text-align:left">Flink 的代码仓库是： <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FwYWNoZS9mbGluaw==" title="https://github.com/apache/flink">https://github.com/apache/flink<i class="fa fa-external-link"></i></span></td>
</tr>
</tbody>
</table>
<p>建议选用社区已发布的稳定分支，比如 Release-1.6 或者 Release-1.7。</p>
<h3 id="1-编译-Flink-代码"><a href="#1-编译-Flink-代码" class="headerlink" title="1. 编译 Flink 代码"></a>1. 编译 Flink 代码</h3><p>在我们配置好之前的几个工具后，编译 Flink 就非常简单了，执行如下命令即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mvn clean install -DskipTests</span><br><span class="line"># 或者</span><br><span class="line">mvn clean package -DskipTests</span><br></pre></td></tr></table></figure>
<p>常用编译参数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">-Dfast    主要是忽略QA plugins和JavaDocs的编译</span><br><span class="line">-Dhadoop.version=2.6.1    指定hadoop版本</span><br><span class="line">--settings=$&#123;maven_file_path&#125;    显式指定maven settings.xml配置文件</span><br></pre></td></tr></table></figure>
<p>当成功编译完成后，能在当前 Flink 代码目录下的 flink-dist/target/子目录 中看到如下文件（不同的 Flink 代码分支编译出的版本号不同，这里的版本号是 Flink 1.5.1）：</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1j6ho5j30j3095tcj.jpg" alt="1"></p>
<p>其中有三个文件可以留意一下：</p>
<table>
<thead>
<tr>
<th style="text-align:left">版本</th>
<th style="text-align:left">注释</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">flink-1.5.1.tar.gz</td>
<td style="text-align:left">Binary 的压缩包</td>
</tr>
<tr>
<td style="text-align:left">flink-1.5.1-bin/flink-1.5.1</td>
<td style="text-align:left">解压后的 Flink binary 目录</td>
</tr>
<tr>
<td style="text-align:left">flink-dist_2.11-1.5.1.jar</td>
<td style="text-align:left">包含 Flink 核心功能的 jar 包</td>
</tr>
</tbody>
</table>
<blockquote>
<p>注意：</p>
</blockquote>
<p>国内用户在编译时可能遇到编译失败“Build Failure”（且有 MapR 相关报错），一般都和 MapR 相关依赖的下载失败有关，即使使用了推荐的 settings.xml 配置（其中 Aliyun Maven 源专门为 MapR 相关依赖做了代理），还是可能出现下载失败的情况。问题主要和 MapR 的 Jar 包比较大有关。遇到这些问题时，重试即可。在重试之前，要先根据失败信息删除 Maven local repository 中对应的目录，否则需要等待 Maven 下载的超时时间才能再次出发下载依赖到本地。</p>
<h3 id="2-开发环境准备"><a href="#2-开发环境准备" class="headerlink" title="2. 开发环境准备"></a>2. 开发环境准备</h3><p>推荐使用 IntelliJ IDEA IDE 作为 Flink 的 IDE 工具。官方不建议使用 Eclipse IDE，主要原因是 Eclipse 的 Scala IDE 和 Flink 用 Scala 的不兼容。</p>
<p>如果你需要做一些 Flink 代码的开发工作，则需要根据 Flink 代码的 tools/maven/目录 下的配置文件来配置 Checkstyle ，因为 Flink 在编译时会强制代码风格的检查，如果代码风格不符合规范，可能会直接编译失败。
 </p>
<h2 id="二、运行-Flink-应用"><a href="#二、运行-Flink-应用" class="headerlink" title="二、运行 Flink 应用"></a>二、运行 Flink 应用</h2><h3 id="1-基本概念"><a href="#1-基本概念" class="headerlink" title="1. 基本概念"></a>1. 基本概念</h3><p>运行 Flink 应用其实非常简单，但是在运行 Flink 应用之前，还是有必要了解 Flink 运行时的各个组件，因为这涉及到 Flink 应用的配置问题。图 1 所示，这是用户用 DataStream API 写的一个数据处理程序。可以看到，在一个 DAG 图中不能被 Chain 在一起的 Operator 会被分隔到不同的 Task 中，也就是说 Task 是 Flink 中资源调度的最小单位。</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1pn7ozj30qs0i40xb.jpg" alt="2"><br>图 1 Parallel Dataflows</p>
<p>图 2 所示，Flink 实际运行时包括两类进程：</p>
<ul>
<li>JobManager（又称为 JobMaster）：协调 Task 的分布式执行，包括调度 Task、协调创 Checkpoint 以及当 Job failover 时协调各个 Task 从 Checkpoint 恢复等。</li>
<li>TaskManager（又称为 Worker）：执行 Dataflow 中的 Tasks，包括内存 Buffer 的分配、Data Stream 的传递等。</li>
</ul>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx1wxus2j30q70jdgqe.jpg" alt="3"></p>
<p>图 2 Flink Runtime 架构图</p>
<p>图 3 所示，Task Slot 是一个 TaskManager 中的最小资源分配单位，一个 TaskManager 中有多少个 Task Slot 就意味着能支持多少并发的 Task 处理。需要注意的是，一个 Task Slot 中可以执行多个 Operator，一般这些 Operator 是能被 Chain 在一起处理的。</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx296yn0j30r209y0v4.jpg" alt="4"><br>图 3 Process</p>
<h3 id="2-运行环境准备"><a href="#2-运行环境准备" class="headerlink" title="2. 运行环境准备"></a>2. 运行环境准备</h3><ul>
<li>准备 Flink binary<br>直接从 Flink 官网上下载 Flink binary 的压缩包</li>
</ul>
<p>或者从 Flink 源码编译而来</p>
<ul>
<li>安装 Java，并配置 JAVA_HOME 环境变量</li>
</ul>
<h3 id="3-单机-Standalone-的方式运行-Flink"><a href="#3-单机-Standalone-的方式运行-Flink" class="headerlink" title="3. 单机 Standalone 的方式运行 Flink"></a>3. 单机 Standalone 的方式运行 Flink</h3><h4 id="（1）基本的启动流程"><a href="#（1）基本的启动流程" class="headerlink" title="（1）基本的启动流程"></a>（1）基本的启动流程</h4><p>最简单的运行 Flink 应用的方法就是以单机 Standalone 的方式运行。</p>
<p>启动集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/start-cluster.sh</span><br></pre></td></tr></table></figure>
<p>打开 <span class="exturl" data-url="aHR0cDovLzEyNy4wLjAuMTo4MDgxLw==" title="http://127.0.0.1:8081/">http://127.0.0.1:8081/<i class="fa fa-external-link"></i></span> 就能看到 Flink 的 Web 界面。尝试提交 Word Count 任务：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar</span><br></pre></td></tr></table></figure>
<p>大家可以自行探索 Web 界面中展示的信息，比如，我们可以看看 TaskManager 的 stdout 日志，就可以看到 Word Count 的计算结果。</p>
<p>我们还可以尝试通过“–input”参数指定我们自己的本地文件作为输入，然后执行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar --input $&#123;your_source_file&#125;</span><br></pre></td></tr></table></figure>
<p>停止集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/stop-cluster.sh</span><br></pre></td></tr></table></figure>
<h4 id="（2）常用配置介绍"><a href="#（2）常用配置介绍" class="headerlink" title="（2）常用配置介绍"></a>（2）常用配置介绍</h4><ul>
<li>conf / slaves</li>
</ul>
<p>conf / slaves 用于配置 TaskManager 的部署，默认配置下只会启动一个 TaskManager 进程，如果想增加一个 TaskManager 进程的，只需要文件中追加一行“localhost”。</p>
<p>也可以直接通过“ ./bin/taskmanager.sh start ”这个命令来追加一个新的 TaskManager：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/taskmanager.sh start|start-foreground|stop|stop-all</span><br></pre></td></tr></table></figure>
<ul>
<li>conf/flink-conf.yaml</li>
</ul>
<p>conf/flink-conf.yaml 用于配置 JM 和 TM 的运行参数，常用配置有：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># The heap size for the JobManager JVM</span><br><span class="line">jobmanager.heap.mb: 1024</span><br><span class="line"></span><br><span class="line"># The heap size for the TaskManager JVM</span><br><span class="line">taskmanager.heap.mb: 1024</span><br><span class="line"></span><br><span class="line"># The number of task slots that each TaskManager offers. Each slot runs one parallel pipeline.</span><br><span class="line">taskmanager.numberOfTaskSlots: 4</span><br><span class="line"></span><br><span class="line"># the managed memory size for each task manager.</span><br><span class="line">taskmanager.managed.memory.size: 256</span><br></pre></td></tr></table></figure>
<p>Standalone 集群启动后，我们可以尝试分析一下 Flink 相关进程的运行情况。执行 jps 命令，可以看到 Flink 相关的进程主要有两个，一个是 JobManager 进程，另一个是 TaskManager 进程。我们可以进一步用 ps 命令看看进程的启动参数中“-Xmx”和“-Xms”的配置。然后我们可以尝试修改 flink-conf.yaml 中若干配置，然后重启 Standalone 集群看看发生了什么变化。</p>
<p>需要补充的是，在 Blink 开源分支上，TaskManager 的内存计算上相对于现在的社区版本要更精细化，TaskManager 进程的堆内存限制（-Xmx）一般的计算方法是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TotalHeapMemory = taskmanager.heap.mb + taskmanager.managed.memory.size + taskmanager.process.heap.memory.mb（默认值为128MB）</span><br></pre></td></tr></table></figure>
<p>而最新的 Flink 社区版本 Release-1.7 中 JobManager 和 TaskManager 默认内存配置方式为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># The heap size for the JobManager JVM</span><br><span class="line">jobmanager.heap.size: 1024m</span><br><span class="line"></span><br><span class="line"># The heap size for the TaskManager JVM</span><br><span class="line">taskmanager.heap.size: 1024m</span><br></pre></td></tr></table></figure>
<p>Flink 社区 Release-1.7 版本中的“taskmanager.heap.size”配置实际上指的不是 Java heap 的内存限制，而是 TaskManager 进程总的内存限制。我们可以同样用上述方法查看 Release-1.7 版本的 Flink binary 启动的 TaskManager 进程的 -Xmx 配置，会发现实际进程上的 -Xmx 要小于配置的“taskmanager.heap.size”的值，原因在于从中扣除了 Network buffer 用的内存，因为 Network buffer 用的内存一定是 Direct memory，所以不应该算在堆内存限制中。</p>
<h4 id="（3）日志的查看和配置"><a href="#（3）日志的查看和配置" class="headerlink" title="（3）日志的查看和配置"></a>（3）日志的查看和配置</h4><p>JobManager 和 TaskManager 的启动日志可以在 Flink binary 目录下的 Log 子目录中找到。Log 目录中以“flink-${user}-standalonesession-${id}-${hostname}”为前缀的文件对应的是 JobManager 的输出，其中有三个文件：</p>
<ul>
<li>flink-${user}-standalonesession-${id}-${hostname}.log：代码中的日志输出</li>
<li>flink-${user}-standalonesession-${id}-${hostname}.out：进程执行时的stdout输出</li>
<li>flink-${user}-standalonesession-${id}-${hostname}-gc.log：JVM的GC的日志</li>
</ul>
<p>Log 目录中以“flink-${user}-taskexecutor-${id}-${hostname}”为前缀的文件对应的是 TaskManager 的输出，也包括三个文件，和 JobManager 的输出一致。</p>
<p>日志的配置文件在 Flink binary 目录的 conf 子目录下，其中：</p>
<ul>
<li>log4j-cli.properties：用 Flink 命令行时用的 log 配置，比如执行“ flink run”命令</li>
<li>log4j-yarn-session.properties：用 yarn-session.sh 启动时命令行执行时用的 log 配置</li>
<li>log4j.properties：无论是 Standalone 还是 Yarn 模式，JobManager 和 TaskManager 上用的 log 配置都是 log4j.properties</li>
</ul>
<p>这三个“log4j.<em>properties”文件分别有三个“logback.</em>xml”文件与之对应，如果想使用 Logback 的同学，之需要把与之对应的“log4j.*properties”文件删掉即可，对应关系如下：</p>
<ul>
<li>log4j-cli.properties -&gt; logback-console.xml</li>
<li>log4j-yarn-session.properties -&gt; logback-yarn.xml</li>
<li>log4j.properties -&gt; logback.xml</li>
</ul>
<p>需要注意的是，“flink-${user}-standalonesession-${id}-${hostname}”和“flink-${user}-taskexecutor-${id}-${hostname}”都带有“${id}”，“${id}”表示本进程在本机上该角色（JobManager 或 TaskManager）的所有进程中的启动顺序，默认从 0 开始。</p>
<h4 id="（4）进一步探索"><a href="#（4）进一步探索" class="headerlink" title="（4）进一步探索"></a>（4）进一步探索</h4><p>尝试重复执行“./bin/start-cluster.sh”命令，然后看看 Web 页面（或者执行jps命令），看看会发生什么？可以尝试看看启动脚本，分析一下原因。接着可以重复执行“./bin/stop-cluster.sh”，每次执行完后，看看会发生什么。</p>
<h3 id="4-多机部署-Flink-Standalone-集群"><a href="#4-多机部署-Flink-Standalone-集群" class="headerlink" title="4. 多机部署 Flink Standalone 集群"></a>4. 多机部署 Flink Standalone 集群</h3><p>部署前要注意的要点：</p>
<ul>
<li>每台机器上配置好 Java 以及 JAVA_HOME 环境变量</li>
<li>每台机器上部署的 Flink binary 的目录要保证是同一个目录</li>
<li>如果需要用 HDFS，需要配置 HADOOP_CONF_DIR 环境变量配置</li>
</ul>
<p>根据你的集群信息修改 conf/masters 和 conf/slaves 配置。</p>
<p>修改 conf/flink-conf.yaml 配置，注意要确保和 Masters 文件中的地址一致：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jobmanager.rpc.address: z05f06378.sqa.zth.tbsite.net</span><br></pre></td></tr></table></figure>
<p>确保所有机器的 Flink binary 目录中 conf 中的配置文件相同，特别是以下三个：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">conf/masters</span><br><span class="line">conf/slaves</span><br><span class="line">conf/flink-conf.yaml</span><br></pre></td></tr></table></figure>
<p>然后启动 Flink 集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/start-cluster.sh</span><br></pre></td></tr></table></figure>
<p>提交 WordCount 作业：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar</span><br></pre></td></tr></table></figure>
<p>上传 WordCount 的 Input 文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hdfs dfs -copyFromLocal story /test_dir/input_dir/story</span><br></pre></td></tr></table></figure>
<p>提交读写 HDFS 的 WordCount 作业：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar --input hdfs:///test_dir/input_dir/story --output hdfs:///test_dir/output_dir/output</span><br></pre></td></tr></table></figure>
<p>增加 WordCount 作业的并发度（注意输出文件重名会提交失败）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar --input hdfs:///test_dir/input_dir/story --output hdfs:///test_dir/output_dir/output --parallelism 20</span><br></pre></td></tr></table></figure>
<h3 id="5-Standalone-模式的-HighAvailability（HA）部署和配置"><a href="#5-Standalone-模式的-HighAvailability（HA）部署和配置" class="headerlink" title="5. Standalone 模式的 HighAvailability（HA）部署和配置"></a>5. Standalone 模式的 HighAvailability（HA）部署和配置</h3><p>通过图 2 Flink Runtime 架构图，我们可以看到 JobManager 是整个系统中最可能导致系统不可用的角色。如果一个 TaskManager 挂了，在资源足够的情况下，只需要把相关 Task 调度到其他空闲 TaskSlot 上，然后 Job 从 Checkpoint 中恢复即可。而如果当前集群中只配置了一个 JobManager，则一旦 JobManager 挂了，就必须等待这个 JobManager 重新恢复，如果恢复时间过长，就可能导致整个 Job 失败。</p>
<p>因此如果在生产业务使用 Standalone 模式，则需要部署配置 HighAvailability，这样同时可以有多个 JobManager 待命，从而使得 JobManager 能够持续服务。</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx2lsgn1j30ez0cy414.jpg" alt="5"><br>图 4 Flink JobManager HA 示意图</p>
<blockquote>
<p>注意：</p>
</blockquote>
<ul>
<li>如果想使用 Flink standalone HA 模式，需要确保基于 Flink Release-1.6.1 及以上版本，因为这里社区有个 bug 会导致这个模式下主 JobManager 不能正常工作。</li>
<li>接下来的实验中需要用到 HDFS，所以需要下载带有 Hadoop 支持的 Flink Binary 包。</li>
</ul>
<h4 id="（1）（可选）使用-Flink-自带的脚本部署-ZK"><a href="#（1）（可选）使用-Flink-自带的脚本部署-ZK" class="headerlink" title="（1）（可选）使用 Flink 自带的脚本部署 ZK"></a>（1）（可选）使用 Flink 自带的脚本部署 ZK</h4><p>Flink 目前支持基于 Zookeeper 的 HA。如果你的集群中没有部署 ZK，Flink 提供了启动 Zookeeper 集群的脚本。首先修改配置文件“conf/zoo.cfg”，根据你要部署的 Zookeeper Server 的机器数来配置“server.X=addressX:peerPort:leaderPort”，其中“X”是一个 Zookeeper Server的唯一 ID，且必须是数字。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># The port at which the clients will connect</span><br><span class="line">clientPort=3181</span><br><span class="line"></span><br><span class="line">server.1=z05f06378.sqa.zth.tbsite.net:4888:5888</span><br><span class="line">server.2=z05c19426.sqa.zth.tbsite.net:4888:5888</span><br><span class="line">server.3=z05f10219.sqa.zth.tbsite.net:4888:5888</span><br></pre></td></tr></table></figure>
<p>然后启动 Zookeeper：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/start-zookeeper-quorum.sh</span><br></pre></td></tr></table></figure>
<p>jps 命令看到 ZK 进程已经启动：</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx31jdnsj30fg034jrn.jpg" alt="7"></p>
<p>停掉 Zookeeper 集群的命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/stop-zookeeper-quorum.sh</span><br></pre></td></tr></table></figure>
<p> </p>
<h4 id="（2）修改-Flink-Standalone-集群的配置"><a href="#（2）修改-Flink-Standalone-集群的配置" class="headerlink" title="（2）修改 Flink Standalone 集群的配置"></a>（2）修改 Flink Standalone 集群的配置</h4><p>修改 conf/masters 文件，增加一个 JobManager：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$cat conf/masters</span><br><span class="line">z05f06378.sqa.zth.tbsite.net:8081</span><br><span class="line">z05c19426.sqa.zth.tbsite.net:8081</span><br></pre></td></tr></table></figure>
<p>之前修改过的 conf/slaves 文件保持不变：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$cat conf/slaves</span><br><span class="line">z05f06378.sqa.zth.tbsite.net</span><br><span class="line">z05c19426.sqa.zth.tbsite.net</span><br><span class="line">z05f10219.sqa.zth.tbsite.net</span><br></pre></td></tr></table></figure>
<p>修改 conf/flink-conf.yaml 文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"># 配置high-availability mode</span><br><span class="line">high-availability: zookeeper</span><br><span class="line"></span><br><span class="line"># 配置zookeeper quorum（hostname和端口需要依据对应zk的实际配置）</span><br><span class="line">high-availability.zookeeper.quorum: z05f02321.sqa.zth.tbsite.net:2181,z05f10215.sqa.zth.tbsite.net:2181</span><br><span class="line"></span><br><span class="line"># （可选）设置zookeeper的root目录</span><br><span class="line">high-availability.zookeeper.path.root: /test_dir/test_standalone2_root</span><br><span class="line"></span><br><span class="line"># （可选）相当于是这个standalone集群中创建的zk node的namespace</span><br><span class="line">high-availability.cluster-id: /test_dir/test_standalone2</span><br><span class="line"></span><br><span class="line"># JobManager的meta信息放在dfs，在zk上主要会保存一个指向dfs路径的指针</span><br><span class="line">high-availability.storageDir: hdfs:///test_dir/recovery2/</span><br></pre></td></tr></table></figure>
<p>需要注意的是，在 HA 模式下 conf/flink-conf.yaml 中的这两个配置都失效了（想想为什么）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">jobmanager.rpc.address</span><br><span class="line">jobmanager.rpc.port</span><br></pre></td></tr></table></figure>
<p>修改完成后，确保配置同步到其他机器。</p>
<p>启动 Zookeeper 集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/start-zookeeper-quorum.sh</span><br></pre></td></tr></table></figure>
<p>再启动 Standalone 集群（要确保之前的 Standalone 集群已经停掉）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/start-cluster.sh</span><br></pre></td></tr></table></figure>
<p>分别打开两个 Master 节点上的 JobManager Web 页面：</p>
<p><span class="exturl" data-url="aHR0cDovL3owNWYwNjM3OC5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05f06378.sqa.zth.tbsite.net:8081/">http://z05f06378.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span><br><span class="exturl" data-url="aHR0cDovL3owNWMxOTQyNi5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05c19426.sqa.zth.tbsite.net:8081/">http://z05c19426.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span></p>
<p>可以看到两个页面最后都转到了同一个地址上，这个地址就是当前主 JobManager 所在机器，另一个就是 Standby JobManager。以上我们就完成了 Standalone 模式下 HA 的配置。</p>
<p>接下来我们可以测试验证 HA 的有效性。当我们知道主 JobManager 的机器后，我们可以把主 JobManager 进程 Kill 掉，比如当前主 JobManager 在 z05c19426.sqa.zth.tbsite.net 这个机器上，就把这个进程杀掉。</p>
<p>接着，再打开这两个链接：<br><span class="exturl" data-url="aHR0cDovL3owNWYwNjM3OC5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05f06378.sqa.zth.tbsite.net:8081/">http://z05f06378.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span><br><span class="exturl" data-url="aHR0cDovL3owNWMxOTQyNi5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05c19426.sqa.zth.tbsite.net:8081/">http://z05c19426.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span></p>
<p>可以发现后一个链接已经不能展示了，而前一个链接可以展示，说明发生主备切换。<br>然后我们再重启前一次的主 JobManager：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/jobmanager.sh start z05c19426.sqa.zth.tbsite.net 8081</span><br></pre></td></tr></table></figure>
<p>再打开 <span class="exturl" data-url="aHR0cDovL3owNWMxOTQyNi5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05c19426.sqa.zth.tbsite.net:8081/">http://z05c19426.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span> 这个链接，会发现现在这个链接可以转到 <span class="exturl" data-url="aHR0cDovL3owNWYwNjM3OC5zcWEuenRoLnRic2l0ZS5uZXQ6ODA4MS8=" title="http://z05f06378.sqa.zth.tbsite.net:8081/">http://z05f06378.sqa.zth.tbsite.net:8081<i class="fa fa-external-link"></i></span> 这个页面上了。说明这个 JobManager 完成了一个 Failover Recovery。</p>
<h3 id="6-使用-Yarn-模式跑-Flink-job"><a href="#6-使用-Yarn-模式跑-Flink-job" class="headerlink" title="6. 使用 Yarn 模式跑 Flink job"></a>6. 使用 Yarn 模式跑 Flink job</h3><p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmtx37snbbj30po0bsmz7.jpg" alt="8"></p>
<p>图 5 Flink Yarn 部署流程图</p>
<p>相对于 Standalone 模式，Yarn 模式允许 Flink job 的好处有：</p>
<ul>
<li>资源按需使用，提高集群的资源利用率</li>
<li>任务有优先级，根据优先级运行作业</li>
<li>基于 Yarn 调度系统，能够自动化地处理各个角色的 Failover<br>○ JobManager 进程和 TaskManager 进程都由 Yarn NodeManager 监控</li>
</ul>
<p>○ 如果 JobManager 进程异常退出，则 Yarn ResourceManager 会重新调度 JobManager 到其他机器<br>○ 如果 TaskManager 进程异常退出，JobManager 会收到消息并重新向 Yarn ResourceManager 申请资源，重新启动 TaskManager</p>
<h4 id="（1）在-Yarn-上启动-Long-Running-的-Flink-集群（Session-Cluster-模式）"><a href="#（1）在-Yarn-上启动-Long-Running-的-Flink-集群（Session-Cluster-模式）" class="headerlink" title="（1）在 Yarn 上启动 Long Running 的 Flink 集群（Session Cluster 模式）"></a>（1）在 Yarn 上启动 Long Running 的 Flink 集群（Session Cluster 模式）</h4><p>查看命令参数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/yarn-session.sh -h</span><br></pre></td></tr></table></figure>
<p>创建一个 Yarn 模式的 Flink 集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/yarn-session.sh -n 4 -jm 1024m -tm 4096m</span><br></pre></td></tr></table></figure>
<p>其中用到的参数是：</p>
<ul>
<li>-n,–container Number of TaskManagers</li>
<li>-jm,–jobManagerMemory Memory for JobManager Container with optional unit (default: MB)</li>
<li>-tm,–taskManagerMemory Memory per TaskManager Container with optional unit (default: MB)</li>
<li>-qu,–queue Specify YARN queue.</li>
<li>-s,–slots Number of slots per TaskManager</li>
<li>-t,–ship Ship files in the specified directory (t for transfer)</li>
</ul>
<p>提交一个 Flink job 到 Flink 集群：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run examples/streaming/WordCount.jar --input hdfs:///test_dir/input_dir/story --output hdfs:///test_dir/output_dir/output</span><br></pre></td></tr></table></figure>
<p>这次提交 Flink job，虽然没有指定对应 Yarn application 的信息，却可以提交到对应的 Flink 集群，原因在于“/tmp/.yarn-properties-${user}”文件中保存了上一次创建 Yarn session 的集群信息。所以如果同一用户在同一机器上再次创建一个 Yarn session，则这个文件会被覆盖掉。</p>
<ul>
<li>如果删掉“/tmp/.yarn-properties-${user}”或者在另一个机器上提交作业能否提交到预期到yarn session中呢？<br>可以配置了“high-availability.cluster-id”参数，据此从 Zookeeper 上获取到 JobManager 的地址和端口，从而提交作业。</li>
<li>如果 Yarn session 没有配置 HA，又该如何提交呢？</li>
</ul>
<p>这个时候就必须要在提交 Flink job 的命令中指明 Yarn 上的 Application ID，通过“-yid”参数传入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/bin/flink run -yid application_1548056325049_0048 examples/streaming/WordCount.jar --input hdfs:///test_dir/input_dir/story --output hdfs:///test_dir/output_dir/output</span><br></pre></td></tr></table></figure>
<p>我们可以发现，每次跑完任务不久，TaskManager 就被释放了，下次在提交任务的时候，TaskManager 又会重新拉起来。如果希望延长空闲 TaskManager 的超时时间，可以在 conf/flink-conf.yaml 文件中配置下面这个参数，单位是 milliseconds：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">slotmanager.taskmanager-timeout: 30000L         # deprecated, used in release-1.5</span><br><span class="line">resourcemanager.taskmanager-timeout: 30000L</span><br></pre></td></tr></table></figure>
<h4 id="（2）在-Yarn-上运行单个-Flink-job（Job-Cluster-模式）"><a href="#（2）在-Yarn-上运行单个-Flink-job（Job-Cluster-模式）" class="headerlink" title="（2）在 Yarn 上运行单个 Flink job（Job Cluster 模式）"></a>（2）在 Yarn 上运行单个 Flink job（Job Cluster 模式）</h4><p>如果你只想运行单个 Flink Job 后就退出，那么可以用下面这个命令：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run -m yarn-cluster -yn 2 examples/streaming/WordCount.jar --input hdfs:///test_dir/input_dir/story --output hdfs:///test_dir/output_dir/output</span><br></pre></td></tr></table></figure>
<p>常用的配置有：</p>
<ul>
<li>-yn,–yarncontainer Number of Task Managers</li>
<li>-yqu,–yarnqueue Specify YARN queue.</li>
<li>-ys,–yarnslots Number of slots per TaskManager</li>
<li>-yqu,–yarnqueue Specify YARN queue.</li>
</ul>
<p>可以通过 Help 命令查看 Run 的可用参数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./bin/flink run -h</span><br></pre></td></tr></table></figure>
<p>我们可以看到，“./bin/flink run -h”看到的“Options for yarn-cluster mode”中的“-y”和“–yarn”为前缀的参数其实和“./bin/yarn-session.sh -h”命令是一一对应的，语义上也基本一致。</p>
<p>关于“-n”（在yarn session模式下）、“-yn”在（yarn single job模式下）与“-p”参数的关系：</p>
<ul>
<li>“-n”和“-yn”在社区版本中（Release-1.5 ～ Release-1.7）中没有实际的控制作用，实际的资源是根据“-p”参数来申请的，并且 TM 使用完后就会归还</li>
<li>在 Blink 的开源版本中，“-n”（在 Yarn Session 模式下）的作用就是一开始启动指定数量的 TaskManager，之后即使 Job 需要更多的 Slot，也不会申请新的 TaskManager</li>
<li>在 Blink 的开源版本中，Yarn single job 模式“-yn”表示的是初始 TaskManager 的数量，不设置 TaskManager 的上限。（需要特别注意的是，只有加上“-yd”参数才能用 Single job 模式（例如：命令“./bin/flink run -yd -m yarn-cluster xxx”）</li>
</ul>
<h3 id="7-Yarn-模式下的-HighAvailability-配置"><a href="#7-Yarn-模式下的-HighAvailability-配置" class="headerlink" title="7. Yarn 模式下的 HighAvailability 配置"></a>7. Yarn 模式下的 HighAvailability 配置</h3><p>首先要确保启动 Yarn 集群用的“yarn-site.xml”文件中的这个配置，这个是 Yarn 集群级别 AM 重启的上限。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"> &lt;property&gt;</span><br><span class="line">  &lt;name&gt;yarn.resourcemanager.am.max-attempts&lt;/name&gt;</span><br><span class="line">  &lt;value&gt;100&lt;/value&gt;</span><br><span class="line">&lt;/property&gt;</span><br></pre></td></tr></table></figure>
<p>然后在 conf/flink-conf.yaml 文件中配置这个 Flink job 的 JobManager 能够重启的次数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yarn.application-attempts: 10     # 1+ 9 retries</span><br></pre></td></tr></table></figure>
<p>最后再在 conf/flink-conf.yaml 文件中配置上 ZK 相关配置，这几个配置的配置方法和 Standalone 的 HA 配置方法基本一致，如下所示。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"># 配置high-availability mode</span><br><span class="line">high-availability: zookeeper</span><br><span class="line"></span><br><span class="line"># 配置zookeeper quorum（hostname和端口需要依据对应zk的实际配置）</span><br><span class="line">high-availability.zookeeper.quorum: z05f02321.sqa.zth.tbsite.net:2181,z05f10215.sqa.zth.tbsite.net:2181</span><br><span class="line"></span><br><span class="line"># （可选）设置zookeeper的root目录</span><br><span class="line">high-availability.zookeeper.path.root: /test_dir/test_standalone2_root</span><br><span class="line"></span><br><span class="line"># 删除这个配置</span><br><span class="line"># high-availability.cluster-id: /test_dir/test_standalone2</span><br><span class="line"></span><br><span class="line"># JobManager的meta信息放在dfs，在zk上主要会保存一个指向dfs路径的指针</span><br><span class="line">high-availability.storageDir: hdfs:///test_dir/recovery2/</span><br></pre></td></tr></table></figure>
<p>需要特别注意的是：“high-availability.cluster-id”这个配置最好去掉，因为在 Yarn（以及Mesos）模式下，cluster-id 如果不配置的话，会配置成 Yarn 上的 Application ID ，从而可以保证唯一性。</p>
<p><span class="exturl" data-url="aHR0cHM6Ly9kZXZlbG9wZXIuYWxpeXVuLmNvbS9hcnRpY2xlLzcxMjcwMj9zcG09YTJjNmguMTI4NzM2MzkuMC4wLjUyMDFmNTUzR3p0aE9hJmFtcDtncm91cENvZGU9c2M=" title="https://developer.aliyun.com/article/712702?spm=a2c6h.12873639.0.0.5201f553GzthOa&amp;groupCode=sc">原文地址<i class="fa fa-external-link"></i></span></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        
          
        
        <div class="post-tags">
          
            <a href="/tags/Flink/" rel="tag"><i class="fa fa-tag"></i> Flink</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
              <div>
                

<script src="//cdn.jsdelivr.net/npm/ilyabirman-likely@2/release/likely.js"></script>



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/ilyabirman-likely@2/release/likely.css">


  


<div class="likely likely-light">
	
 	 	<div class="twitter">Tweet</div>
	
 	 	<div class="facebook">Share</div>
	
 	 	<div class="linkedin">Link</div>
	
 	 	<div class="gplus">Plus</div>
	
 	 	<div class="vkontakte">Share</div>
	
 	 	<div class="odnoklassniki">Class</div>
	
 	 	<div class="telegram">Send</div>
	
 	 	<div class="whatsapp">Send</div>
	
 	 	<div class="pinterest">Pin</div>
	
</div>

              </div>
            
            
            
              <div>
                
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

              </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Apache Flink 零基础入门（一）：基础概念解析.html" rel="next" title="Apache Flink 零基础入门（一）：基础概念解析">
                <i class="fa fa-chevron-left"></i> Apache Flink 零基础入门（一）：基础概念解析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Apache Flink 零基础入门（三）：DataStream API 编程.html" rel="prev" title="Apache Flink 零基础入门（三）：DataStream API 编程">
                Apache Flink 零基础入门（三）：DataStream API 编程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk3My82NTM4"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://hexoblog-1254111960.cos.ap-guangzhou.myqcloud.com/HexoBlog-tou.jpg" alt="Daniel X">
            
              <p class="site-author-name" itemprop="name">Daniel X</p>
              <div class="site-description motion-element" itemprop="description">專注于大数据技術，分享干货</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">125</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">63</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2R1ZGVmdQ==" title="GitHub &rarr; https://github.com/dudefu"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOmR1ZGVmdUBmb3htYWlsLmNvbT9zdWJqZWN0PUhlbGxvJTIwYWdhaW4=" title="E-mail &rarr; mailto:dudefu@foxmail.com?subject=Hello%20again"><i class="fa fa-fw fa-envelope"></i>E-mail</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly93ZWliby5jb20vZHVkZWZ1" title="Weibo &rarr; https://weibo.com/dudefu"><i class="fa fa-fw fa-weibo"></i>Weibo</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly93cGEucXEuY29tL21zZ3JkP3Y9MyZ1aW49MTU3NzU3MTk1OSZzaXRlPWR1ZGVmdS5pbmZvJm1lbnU9eWVz" title="QQ &rarr; https://wpa.qq.com/msgrd?v=3&uin=1577571959&site=dudefu.info&menu=yes"><i class="fa fa-fw fa-qq"></i>QQ</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一、Flink-开发环境部署和配置"><span class="nav-number">2.</span> <span class="nav-text">一、Flink 开发环境部署和配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-编译-Flink-代码"><span class="nav-number">2.1.</span> <span class="nav-text">1. 编译 Flink 代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-开发环境准备"><span class="nav-number">2.2.</span> <span class="nav-text">2. 开发环境准备</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、运行-Flink-应用"><span class="nav-number">3.</span> <span class="nav-text">二、运行 Flink 应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-基本概念"><span class="nav-number">3.1.</span> <span class="nav-text">1. 基本概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-运行环境准备"><span class="nav-number">3.2.</span> <span class="nav-text">2. 运行环境准备</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-单机-Standalone-的方式运行-Flink"><span class="nav-number">3.3.</span> <span class="nav-text">3. 单机 Standalone 的方式运行 Flink</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#（1）基本的启动流程"><span class="nav-number">3.3.1.</span> <span class="nav-text">（1）基本的启动流程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（2）常用配置介绍"><span class="nav-number">3.3.2.</span> <span class="nav-text">（2）常用配置介绍</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（3）日志的查看和配置"><span class="nav-number">3.3.3.</span> <span class="nav-text">（3）日志的查看和配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（4）进一步探索"><span class="nav-number">3.3.4.</span> <span class="nav-text">（4）进一步探索</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-多机部署-Flink-Standalone-集群"><span class="nav-number">3.4.</span> <span class="nav-text">4. 多机部署 Flink Standalone 集群</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-Standalone-模式的-HighAvailability（HA）部署和配置"><span class="nav-number">3.5.</span> <span class="nav-text">5. Standalone 模式的 HighAvailability（HA）部署和配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#（1）（可选）使用-Flink-自带的脚本部署-ZK"><span class="nav-number">3.5.1.</span> <span class="nav-text">（1）（可选）使用 Flink 自带的脚本部署 ZK</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（2）修改-Flink-Standalone-集群的配置"><span class="nav-number">3.5.2.</span> <span class="nav-text">（2）修改 Flink Standalone 集群的配置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-使用-Yarn-模式跑-Flink-job"><span class="nav-number">3.6.</span> <span class="nav-text">6. 使用 Yarn 模式跑 Flink job</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#（1）在-Yarn-上启动-Long-Running-的-Flink-集群（Session-Cluster-模式）"><span class="nav-number">3.6.1.</span> <span class="nav-text">（1）在 Yarn 上启动 Long Running 的 Flink 集群（Session Cluster 模式）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#（2）在-Yarn-上运行单个-Flink-job（Job-Cluster-模式）"><span class="nav-number">3.6.2.</span> <span class="nav-text">（2）在 Yarn 上运行单个 Flink job（Job Cluster 模式）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-Yarn-模式下的-HighAvailability-配置"><span class="nav-number">3.7.</span> <span class="nav-text">7. Yarn 模式下的 HighAvailability 配置</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">粤ICP备18110871号 </span>&copy; 2017 – <span itemprop="copyrightYear">2021</span>
  <span class="with-love" id="animate">
    <i class="fa fa-spinner"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">dudefu</span>

  

  
</div>

<!--

  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Pisces</span> v7.1.2</div>

-->



        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  
    
    
      
    
  
  <script color="26,26,26" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script>









  
  
  <script id="ribbon" size="300" alpha="0.6" zindex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>



  



  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/lib/reading_progress/reading_progress.js"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  
  <script src="/js/js.cookie.js?v=7.1.2"></script>
  <script src="/js/scroll-cookie.js?v=7.1.2"></script>


  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: true,
    notify: true,
    appId: '1N5rpk874DGudJw2wCL9J011-gzGzoHsz',
    appKey: '9Y83e6suJgx567wtxhKy45IN',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: true,
    lang: 'zk-cn' || 'zh-cn'
  });
</script>




  
    <script>
  window.livereOptions = {
    refer: 'Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行.html'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.core.min.js"></script>
  
  <script>
    (function () {

      firebase.initializeApp({
        apiKey: '',
        projectId: ''
      })

      function getCount(doc, increaseCount) {
        //increaseCount will be false when not in article page

        return doc.get().then(function (d) {
          var count
          if (!d.exists) { //has no data, initialize count
            if (increaseCount) {
              doc.set({
                count: 1
              })
              count = 1
            }
            else {
              count = 0
            }
          }
          else { //has data
            count = d.data().count
            if (increaseCount) {
              if (!(window.localStorage && window.localStorage.getItem(title))) { //if first view this article
                doc.set({ //increase count
                  count: count + 1
                })
                count++
              }
            }
          }
          if (window.localStorage && increaseCount) { //mark as visited
            localStorage.setItem(title, true)
          }

          return count
        })
      }

      function appendCountTo(el) {
        return function (count) {
          $(el).append(
            $('<span>').addClass('post-visitors-count').append(
              $('<span>').addClass('post-meta-divider').text('|')
            ).append(
              $('<span>').addClass('post-meta-item-icon').append(
                $('<i>').addClass('fa fa-users')
              )
              ).append($('<span>').text('阅读次数 ' + count))
          )
        }
      }

      var db = firebase.firestore()
      var articles = db.collection('articles')

      //https://hexo.io/docs/variables.html
      var isPost = 'Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行'.length > 0
      var isArchive = '' === 'true'
      var isCategory = ''.length > 0
      var isTag = ''.length > 0

      if (isPost) { //is article page
        var title = 'Apache Flink 零基础入门（二）：开发环境搭建和应用的配置、部署及运行'
        var doc = articles.doc(title)

        getCount(doc, true).then(appendCountTo($('.post-meta')))
      }
      else if (!isArchive && !isCategory && !isTag) { //is index page
        var titles = [] //array to titles

        var postsstr = '' //if you have a better way to get titles of posts, please change it
        eval(postsstr)

        var promises = titles.map(function (title) {
          return articles.doc(title)
        }).map(function (doc) {
          return getCount(doc)
        })
        Promise.all(promises).then(function (counts) {
          var metas = $('.post-meta')
          counts.forEach(function (val, idx) {
            appendCountTo(metas[idx])(val)
          })
        })
      }
    })()
  </script>


  
  

  
  

  


  
<script>
if ($('body').find('div.pdf').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/pdfobject@2/pdfobject.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      $('body').find('div.pdf').each(function(i, o) {
        PDFObject.embed($(o).attr('target'), $(o), {
          pdfOpenParams: {
            navpanes: 0,
            toolbar: 0,
            statusbar: 0,
            pagemode: 'thumbs',
            view: 'FitH'
          },
          PDFJS_URL: '/lib/pdf/web/viewer.html',
          height: $(o).attr('height') || '500px'
        });
      });
    },
  });
}
</script>


  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'dark',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  
  
  
  <script src="/lib/bookmark/bookmark.min.js?v=1.0"></script>
  <script>
  
    bookmark.scrollToMark('auto', "#更多");
  
  </script>


  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      const selection = document.getSelection();
      const selected = selection.rangeCount > 0 ? selection.getRangeAt(0) : false;
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
      if (selected) {
        selection.removeAllRanges();
        selection.addRange(selected);
      }
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
